import { useState, useEffect } from 'react'
import Bottom from "../../components/bottom"
import formatNum from '../../utils/money'
import { Switch, Swiper, Popup, Button, Toast,Empty, } from "antd-mobile"
import ToastBase from "../../components/toast"
import Home from "../../api/home"
import Wish from "../../api/wish"
import style from "./style.module.scss"
import { useLocation, useNavigate } from 'react-router-dom'
import AMapExample from "./searchmap/map"
// import P1 from './searchmap/map'
const { header, search, btn, content, title, housenum, main, totalPrice, goodsItem, proInfo, wishBox, wishItem, map, hopebox } = style
const Explore = () => {
    const navigate = useNavigate()
    const [userid] = useState(sessionStorage.getItem("userid") || "")
    // const [navData, setNavData] = useState([])
    const [obj, setObj] = useState<any>()
    const [toastShow, setToastShow] = useState(false)
    const [img, setImg] = useState("")
    const [wishName, setWishName] = useState<any>()
    const [goodsData, setgoodsData] = useState<any>([])
    const [userGoodsData, setUserGoodsData] = useState<any>([])
    const [wishData, setWishData] = useState<any>([])
    const [visible, setVisible] = useState(false)
    const [visible2, setVisible2] = useState(false)
    const [height, setHeight] = useState(64)
    const [heartArr, setHeartArr] = useState<any>([])
    let [addressinformation, setaddressinformation] = useState([])
    const location = useLocation()
    const [searched] = useState(location.state.info)
    // const [defaultdata,setdefaultdata] = useState([])
    const [startpostation, setstartpostation] = useState(
        [
            {
                title: "黑龙江",
                postation: [126.960866, 47.949808],
                zoom: 6
            },
            {
                title: '辽宁',
                postation: [122.194676, 41.062464],
                zoom: 6.3
            },
            {
                title: '吉林',
                postation: [125.324419, 43.878881],
                zoom: 7
            },
            {
                title: '三亚',
                postation: [109.720345, 18.500908],
                zoom: 8.2
            },
            {
                title: '随便看看',
                postation: [105.634586, 40.760828],
                zoom: 3
            }
        ]
    )

    const getWishData = async () => {
        let res = await Wish["getwList"](userid)
        if (res.status === 200) {
            setWishData(res.data)
            let newArr: any = []
            res.data.forEach((item: any) => {
                item.children.forEach((itm: any) => {
                    newArr = [...newArr, itm.id]
                    setHeartArr(newArr)
                })
            })
        }
    }



    const addWish = async (row: any) => {
        if (sessionStorage.getItem("userid") === null) {
            Toast.show({
                content: "您还没有登录，不能收藏哦~",
                icon: "fail",
                afterClose: () => {
                    navigate("/login")

                }
            })
            return
        }
        getWishData()
        setObj(row)
        setImg(row.banners[0])
        if (row.isHeart) {
            setUserGoodsData(userGoodsData.map((item: any) => {
                if (item.id === row.id) {
                    item.isHeart = false
                }
                return item
            }))
            let res2 = await Wish["removewListChild"]({ userid, proid: row.id })

            if (res2?.code === 200) {
                setWishName({ name1: "删除自", name2: res2.data.data.title })
                setToastShow(true)
                setTimeout(() => {
                    setToastShow(false)
                }, 3000)
            }
        } else {
            setVisible(true)
            setUserGoodsData(userGoodsData.map((item: any) => {
                if (item.id === row.id) {
                    item.isHeart = true
                }
                return item
            }))
        }
    }

    const addWishListChildren = async (row: any) => {

        let res = await Wish["addwListChild"]({ id: row.id, data: [...row.children, obj] })
        if (res.code === 200) {
            setVisible(false)
            setWishName({ name1: "已保存自", name2: row.title })
            setToastShow(true)
            setTimeout(() => {
                setToastShow(false)
            }, 3000)
        }
    }

    const getGoodsData = async () => {
        let res = await Home["getGoods"]()
        if (res.status === 200) {
            // 

            let alladdress: any = []
            let shopbody = []
            for (let a = 0; a < res.data.length; a++) {
                let long = res.data[a].proname.split('、').length - 1
                alladdress.push({ price: res.data[a].price, position: res.data[a].position, loc: res.data[a].proname.split('、')[long] })
            }

            if (searched.place == "随便看看") {
                setaddressinformation(alladdress)
                shopbody = res.data
                setgoodsData(shopbody)
            }
            else if(searched.place == "暂无数据再试试别的看看吧"){
                setaddressinformation(alladdress)
                // shopbody = res.data
                setgoodsData([])
            }
            else {

                setaddressinformation(alladdress.filter((item: any) => { return item.loc === searched.place }))
                shopbody = res.data.filter((item: any) => { return item.proname.split('、')[item.proname.split('、').length - 1] == searched.place })
                console.log(shopbody, "aaaaaaaa");
                setgoodsData(shopbody)
                if(shopbody.length===0){
                    searched.place="暂无数据再试试别的看看吧"
                    getGoodsData()
                }

            }
            setstartpostation(startpostation.filter((item: any) => { return item.title === searched.place }))
        }
    }
    // console.log(goodsData, "aasdasdasdjhhgfjghjk");
    console.log(addressinformation,"hhhhhhhhhhhhhhh");
    console.log(startpostation,'lllllllllllllllllllllllll');
    
    const addWishList = async () => {
        let res = await Wish["addwList"]({ id: userid, children: obj, title: wishName.name2 })
        if (res.code === 200) {
            setVisible2(false)
            setToastShow(true)
            setWishName({ name1: "已保存自", name2: wishName.name2 })
            getGoodsData()
            setTimeout(() => {
                setToastShow(false)
            }, 3000)
        }
    }

    const todetail =(data:any)=>{
        console.log({...data,location:location.state.info},"ingor");
        const proinformation = {...data,location:location.state.info}
        navigate("/details",{state:{proinformation}})
    }

    const showHeart = () => {
        let res = goodsData.map((item: any) => {
            heartArr.map((itm: number) => {
                if (item.id === itm) {
                    item.isHeart = true
                }
            })
            return item
        })
        setUserGoodsData(res)
    }

    useEffect(() => {
        // getNavData()
        getGoodsData()
        getWishData()
    }, [])

    useEffect(() => showHeart(), [goodsData])
    return <div onWheel={(e) => {
        if (e.deltaY > 0) {
            setHeight(0)
        } else {
            setHeight(64)
        }
    }}>

        {
            goodsData.length>0?<div className={header}>
            <div className={search}>
                <div className={content}>
                    <div style={{ flex: "1", display: "flex" }}>
                        <div className={btn}><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true" role="presentation" focusable="false" style={{ display: "block", fill: "none", height: "16px", width: "16px", stroke: "currentcolor", strokeWidth: "4", overflow: "visible" }}><path fill="none" d="M13 24a11 11 0 1 0 0-22 11 11 0 0 0 0 22zm8-3 9 9"></path></svg></div>
                        <div className={title}>
                            <h3>{searched.place}</h3>
                            <div style={{ display: "flex", alignItems: "center" }}> <span>{searched.date}</span><span style={{ paddingLeft: 5, paddingRight: 5 }}>·</span><span>{searched.people}</span></div>
                        </div>
                    </div>
                    <div className={btn}><div style={{ width: "37px", height: "37px", border: "1px solid #ddd", boxSizing: "border-box", display: "flex", alignItems: 'center', justifyContent: "center", borderRadius: "36px" }}><svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 16 16" aria-hidden="true" role="presentation" focusable="false" style={{ display: "block", height: "16px", width: "16px" }}><path d="M5 8a3 3 0 0 1 2.83 2H14v2H7.83A3 3 0 1 1 5 8zm0 2a1 1 0 1 0 0 2 1 1 0 0 0 0-2zm6-8a3 3 0 1 1-2.83 4H2V4h6.17A3 3 0 0 1 11 2zm0 2a1 1 0 1 0 0 2 1 1 0 0 0 0-2z"></path></svg></div></div>
                </div>
            </div>
        </div>:<><Empty style={{position:"absolute",top:240,left:160}}/></>
        }
        <div className={map}>
            <AMapExample searchinformation={addressinformation} startpostation={startpostation}></AMapExample>
            {/* <P1></P1> */}
        </div>
        <div className={main} style={{paddingBottom:200}} >
            <div className={hopebox}>
                <div className={housenum}><span>{goodsData.length}</span>个房源</div>
            </div>
            {
                goodsData.length>0?<div className={totalPrice}>
                <div>
                    <h2>显示总价</h2>
                    <span>税前价格，包含所有费用</span>
                </div>
                <Switch
                    style={{ "--width": "46px", "--checked-color": "#222" }}
                />
            </div>:<Empty style={{marginBottom:50}}/>
            }
            {
                goodsData.map((item: any) => <div key={item.id} className={goodsItem} onClick={()=>{todetail(item)}}>
                    <div style={{ position: 'relative' }}>
                        <Swiper>{item.banners.map((itm: any) => (
                            <Swiper.Item key={itm}>
                                <img src={itm} alt="" />
                            </Swiper.Item>
                        ))}</Swiper>
                        <div style={{ position: 'absolute', top: "15px", right: "15px" }} onClick={() => addWish(item)}>
                            <svg xmlns="http://www.w3.org/2000/svg" viewBox="0 0 32 32" aria-hidden="true" role="presentation" focusable="false" style={{ display: "block", fill: `${item.isHeart ? "#FF385C" : "rgba(0,0,0,0.5)"}`, height: "24px", width: "24px", stroke: "#fff", strokeWidth: 2, overflow: "visible" }}><path d="M16 28c7-4.73 14-10 14-17a6.98 6.98 0 0 0-7-7c-1.8 0-3.58.68-4.95 2.05L16 8.1l-2.05-2.05a6.98 6.98 0 0 0-9.9 0A6.98 6.98 0 0 0 2 11c0 7 7 12.27 14 17z"></path></svg>
                        </div>
                    </div>
                    <div className={proInfo}><p>{item.proname}</p><span>★ {item.score}</span></div>
                    <span>距离你 {item.distance} 公里</span>
                    <div>{item.time}</div>
                    <s>￥{formatNum(item.price)}</s> 晚
                </div>)
            }
            {
                toastShow && <ToastBase img={img} name={wishName} ></ToastBase>
            }
        </div>
        <Bottom height={height} index={0} />

        <Popup
            showCloseButton
            visible={visible}
            onMaskClick={() => {
                setVisible(false)
            }}
            bodyStyle={{
                borderTopLeftRadius: '8px',
                borderTopRightRadius: '8px',
                minHeight: '40vh',
            }}
        >
            <div className={wishBox}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "center", borderBottom: "1px solid #ddd" }}>
                    <h2>你的心愿单</h2>
                </div>
                <div style={{ overflowY: "auto", padding: '20px 16px' }}>
                    <div className={wishItem} onClick={() => { setVisible(false); setVisible2(true) }}>
                        <img src="https://a0.muscache.com/im/pictures/da1a2f06-efb0-4079-abce-0f6fc82089e0.jpg" alt="" />
                        <span>创建新的心愿单</span>
                    </div>
                    {
                        wishData.map((item: any) => <div onClick={() => addWishListChildren(item)} key={item.id} className={wishItem}>
                            <img src={"https://a0.muscache.com/im/pictures/1366a633-171a-4592-9a51-cd4e6f46a897.jpg"} alt="" />
                            <span>{item.title}</span>
                        </div>)
                    }
                </div>
            </div>
        </Popup>
        <Popup
            showCloseButton
            visible={visible2}
            onMaskClick={() => {
                setVisible(false)
            }}
            bodyStyle={{
                borderTopLeftRadius: '8px',
                borderTopRightRadius: '8px',
                minHeight: '40vh',
            }}
        >
            <div className={wishBox}>
                <div style={{ display: "flex", alignItems: "center", justifyContent: "center", borderBottom: "1px solid #ddd" }}>
                    <h2>为此心愿单命名</h2>
                </div>
                <div style={{ padding: "32px 16px", borderBottom: "1px solid #ddd" }}>
                    <input style={{ width: "99%", height: "52px", borderRadius: "10px", textIndent: "10px", border: "2px solid #B0B0B0" }} type="text" placeholder='名称' onChange={(e) => setWishName({ name1: "", name2: e.target.value })} />
                    <span style={{ display: "block", marginTop: "10px", color: "#717171" }}>不能超过50个字符</span>
                </div>
                <Button style={{ margin: "14px 24px", width: "88%", height: "44px", background: "#222", color: "#fff", fontSize: "14px", fontWeight: "bold", borderRadius: "8px" }} disabled={wishName ? false : true} onClick={addWishList}>创建</Button>
            </div>
        </Popup>
    </div>
}
export default Explore